package cn.kgc.providerboosweb.service;

import cn.kgc.entiybookweb.entiy.Book;
import cn.kgc.providerboosweb.mapper.BookMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Service
public class BookServiceMapper implements BookService {
    @Resource
    BookMapper bookMapper;

    @Override
    public String selectBooks(String keyword, Integer keywordtype, Integer pageNum) {
        PageHelper.startPage(pageNum,5);
        PageHelper.orderBy("createDate desc");
        List<Book> books = bookMapper.selectBooks(keyword, keywordtype);
        PageInfo<Book> pageInfo=new PageInfo<>(books);
        String json=null;
        //把pageinfo对象转json
        ObjectMapper mapper=new ObjectMapper();
        try {
            json = mapper.writeValueAsString(pageInfo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public String addBook(Book book) {
        Map<String,Object> map=new HashMap<>();
        int n=bookMapper.addBook(book);
        map.put("statue",n);
        String json=null;
        //把pageinfo对象转json
        ObjectMapper mapper=new ObjectMapper();
        try {
            json = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }
}
